import React, { useState, useEffect, useImperativeHandle } from 'react';
import { Row, Col, Button, Switch, InputNumber } from 'antd';
import { randomKey } from '../../../../utils/utils';
import RuleScoreItem from './ruleScoreItem';
import OtherBtn from './otherBtn';
import { compare } from '../../../../utils/compare';

/**
 * @component RulesScore 评分卡配置组件
 * @prop {Array} value 组件值
 *
 * @prop {Boolean} isShowRules 是否展示具体的配置项 , 默认false
 * @prop {Function} onChange 改变值之后的回调
 * @prop {Object} variable 可被用于选择的变量对象
 * @prop {Boolean} disabled 是否只读,默认false
 * {
    "name": "",
    "left_var_code": "",
    "left_var_type": "field|feature|nameList|strategy|model",
    "left_var_data_type":"",
    "default_score": 20,
    "cases":[
      {
        "min": 0,
        "max": 50,
        "value": "",
        "score": 20
      }
    ],
    "enabled": true
  }
 */

export default function RulesScore(props) {
  const [rules, setRules] = useState(props.value.score_calc_rules);
  const [baseScoreFlag, setBaseScoreFlag] = useState((props.value && props.value.base_score_flag) || false)
  const [baseScore, setBaseScore] = useState((props.value && props.value.base_score) || 0)
  useEffect(() => {
    if (props.value && props.value.score_calc_rules && props.value.score_calc_rules.length > 0) {
      setRules(initData(props.value.score_calc_rules));
    } else {
      addRule();
    }
    setBaseScoreFlag((props.value && props.value.base_score_flag) || false)
    setBaseScore((props.value && props.value.base_score) || 0)
  }, [props.value]);

  useImperativeHandle(props.createRef, () => ({
    // 暴露方法给父组件,收集值，验证应该放到这里，后面再做
    getValue: () => {
      if (baseScoreFlag && baseScore === null  ) throw '请输入基准分'
      return {
        base_score_flag: baseScoreFlag,
        base_score: baseScoreFlag ? baseScore : 0,
        score_calc_rules: rules
      }
    },
  }));

  function initData(data) {
    const newData = data.map((item) => {
      item.id = item.id ? item.id : randomKey();
      return item;
    });
    return newData;
  }

  //添加规则
  function addRule() {
    const rule = {
      name: '',
      left_var_code: '',
      left_var_type: '',
      default_score: 1,
      cases: [],
      enabled: true,
      id: randomKey(),
    };
    rules.push(rule);
    setRules(Object.assign([], rules));
    props.onChange && props.onChange(rules);
  }

  // 修改item的value回调
  function handleChange(id, value) {
    for (let i = 0; i < rules.length; i++) {
      if (rules[i].id === id) {
        rules[i] = value;
      }
    }
    setRules(Object.assign([], rules));
    props.onChange && props.onChange(rules);
  }

  // 删除
  function del(index) {
    rules.splice(index, 1);
    setRules(Object.assign([], rules));
    props.onChange && props.onChange(rules);
  }

  // 移动
  function move(item, index, step) {
    // 下移
    if (step === 'down') {
      rules.splice(index, 1); //移除当前项
      rules.splice(index + 1, 0, item); // 在index+1处插入当前item
      // 上移
    } else if (step === 'up') {
      rules.splice(index, 1); //移除当前项
      rules.splice(index - 1, 0, item); // 在index-1处插入当前item
    }
    setRules(Object.assign([], rules));
    props.onChange && props.onChange(rules);
  }

  return (
    <>
      {!props.hidden && (
        <div style={{ marginTop: '20px' }} className='rule-wp'>
          <Row type='flex' justify='start' align='middle' gutter={10} style={{ marginBottom: '10px' }}>
            {!props.disabled && <>
              <Col>
                <Button
                  type='primary'
                  onClick={() => {
                    addRule();
                  }}
                  disabled={!props.isShowRules}
                >
                  添加规则
                </Button>
              </Col>
              <OtherBtn {...props} onComplete={props.reloadVariable} />
            </>}
            <Col>添加基准分：<Switch checked={baseScoreFlag} onChange={checked => setBaseScoreFlag(checked)} disabled={props.disabled}></Switch></Col>
            {baseScoreFlag && <Col><InputNumber value={baseScore} onChange={value => setBaseScore(value)} max={99999} min={-99999} precision={4} style={compare(props, 'base_score')} disabled={props.disabled}></InputNumber> 分</Col>}
          </Row>
          
          <Row type='flex' justify='space-between' align='middle' gutter={10} className='rule-hd'>
            {!props.disabled && <Col span={1} />}
            <Col span={1}>序号</Col>
            <Col span={3}>变量名</Col>
            <Col span={3}>变量类型</Col>
            <Col span={3}>分箱数</Col>
            <Col span={3}>默认分</Col>
            {!props.disabled && <Col span={3}>操作</Col>}
          </Row>
          {rules.map((item, index) => {
            return (
              <RuleScoreItem
                {...props}
                value={item}
                index={index + 1}
                key={item.id}
                variable={props.variable}
                using_variables={props.using_variables}
                disabled={props.disabled}
                onChange={handleChange.bind(this, item.id)}
                onDel={del.bind(this, index)}
                onMove={move.bind(this, item, index)}
                len={rules.length}
                form={props.form}
                codes={props.codes}
                compareData={(props.compareData && props.compareData.score_calc_rules && props.compareData.score_calc_rules[index]) || []}
                strategyId={props.id}
              />
            );
          })}
        </div>
      )}
    </>
  );
}
